function getQueryString(url, name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = url.match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
function changeURLArg(url, arg, arg_val) {
    var pattern = '[\?\&]+' + arg + '=([^&]*)';
    var replaceText = arg + '=' + arg_val;
    if (url.match(pattern)) {
        return url;
    } else {
        if (url.match('[\?]')) {
            return url + '&' + replaceText;
        } else {
            return url + '?' + replaceText;
        }
    }
}
function isEmpty(value) {
    return (value === null || value == undefined || value === '');
}
function getTokenIdUrl(url) {
    var retSid = getQueryString(url, 'tokenId');
    if (isEmpty(retSid)) {
        retSid = getTokenId();
    }
    if ((url.indexOf('http:') == 0 || url.indexOf('https:') == 0) && url.indexOf(window.location.origin) == -1) {
        return url
    } else {
        return changeURLArg(url, 'tokenId', retSid);
    }
}
hookAjax({
    onreadystatechange: function (xhr) {
        xhr.withCredentials = true;
    },
    onload: function (xhr) {
        xhr.withCredentials = true;
    },
    open: function (arg) {
        arg[1] = getTokenIdUrl(arg[1]);
    },
    send: function (arg) {
    }
})
$(document).ready(function () {
    $('body').append('<input id=${tokenidname} type="hidden" value="${tokenId}" type="hidden"/>');
    $.each($("a"), function (i, link) {
        if (link.href && link.href !== '' && link.href !== 'javascript:;' && link.href !== "") {
            link.href = getTokenIdUrl(link.href)
        }
        var layhref = $(this).attr("lay-href");
        if (layhref && layhref !== '' && layhref !== 'javascript:;' && layhref !== "") {
            layhref = getTokenIdUrl(layhref);
            $(this).attr("lay-href", layhref);
        }
    })
});
function getTokenId() {
    var tokenId = $('#tokenId').val();
    if (!isEmpty(tokenId)) {
        return tokenId;
    }
    var currentWin = parent.window;
    tokenId = $(currentWin.document).find("#tokenId").val();
    while (isEmpty(tokenId) && currentWin) {
        tokenId = $(currentWin.document).find("#tokenId").val();
        currentWin = currentWin.parent;
        if (currentWin === top) { break; }
    }
    return tokenId
}